﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace prufa.Models
{
    public class HighScoreRepository
    {
        DefaultConnection db = new DefaultConnection();
        public void CreateHighScore(int Gameid, int Userid)
        {
            HighScore nytt = new HighScore();
            nytt.GameId = Gameid;
            nytt.GamesPlayed = 0;
            nytt.UserId = Userid;
            nytt.Win = 0;
            db.HighScores.Add(nytt);
            db.SaveChanges();

        }

        public bool CheckIfHighScoreExists(int Gameid, int Userid)
        {
            var temp = (from n in db.HighScores
                    where n.GameId == Gameid && n.UserId == Userid
                    select n).ToList();

            if (temp.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        public void UpdateHighScore(bool WinOrLose, int Gameid, int Userid)
        {
            HighScore temp = (from n in db.HighScores
                              where n.GameId == Gameid && n.UserId == Userid
                              select n).First();

            if (WinOrLose)
            {
                temp.Win += 1;
            }
            temp.GamesPlayed += 1;
            db.SaveChanges();
        }

        public IEnumerable<HighScore> FindHighScoreFromUserId(int Userid)
        {
           IEnumerable<HighScore> temp = (from n in db.HighScores
                              where n.UserId == Userid
                              select n);
           return temp;
        
        }

        public int WinRatio(int userid)
        {
            var wins = from n in db.HighScores
                       where n.UserId == userid
                       select n.Win;
          
            var gamesplayed = from n in db.HighScores
                              where n.UserId == userid
                              select n.GamesPlayed;
            Double winsTotal = 0;
            Double playedTotal = 0;

            foreach(var w in wins)
            {
                winsTotal = winsTotal + (Double)w;                                                      
            }
           foreach(var g in gamesplayed){

                    playedTotal = playedTotal+(Double)g;

                }
           int ttl = (int)((winsTotal / playedTotal) * 100);
            return ttl;
        }
      }
   }
